package admins

import (
	"encoding/json"
	"go_auth/ext/e"
	"go_auth/ext/settings"
	"go_auth/models/admin"
	"go_auth/utils/commons"
	"go_auth/utils/redis"
	"strings"
)

//这里做数据缓存
type Ad struct {
	admin.AdInfo
}

func SetAdToRedis(key, data string, t int) {
	redis.SetStringValue(key, data, t, settings.RDb4)
}

func (a *Ad) Add() int {
	if a.AddAdInfo() == settings.Zero {
		return e.AddError
	}
	return e.Success
}

func UpdateAd(ad []Ad) bool {
	marshal, _ := json.Marshal(ad)
	b := admin.UpdateAd(marshal)
	if b {
		SetAdToRedis("ad", "", 0)
	}

	return b
}

func GetAllAd() ([]byte, int) {
	value, err := redis.GetValue("ad", settings.RDb4)
	if !commons.CheckErr(err) {
		return nil, e.Error
	} else if value != settings.Empty {
		str := strings.Replace(string(value), "\\", "", -1)
		return []byte(str), e.Success
	}
	bytes := admin.GetAllAd()
	SetAdToRedis("ad", string(bytes), 0)
	return bytes, e.Success
}
